package com.example.isoftlangchainai.memorychat;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Date :2025/7/14 16:41
 * @Author :chenjun
 */
@RestController
@RequestMapping("/assistant")
public class AssistantChatController {
    @Value("${langchain4j.open-ai.chat-model.api-key}")
    protected String apikey;
    @Value("${langchain4j.open-ai.chat-model.model-name}")
    protected String modelName;
    @Value("${langchain4j.open-ai.chat-model.base-url}")
    protected String baseUrl;

    //定义AiService代理
    interface Assistant {
//        @SystemMessage("You are a good friend of mine. Answer using slang.")
//        @UserMessage("You are a good friend of mine. Answer using slang. {{it}}")
        String chat(String message);
    }
    
    /**
     *
     * [描述]: 记忆聊天
     */
    @GetMapping ("/chat")
    public String getChat() {
        String answerWithName = "抱歉,我不理解你的意思.";
        try {
            ChatMemory chatMemory = MessageWindowChatMemory.withMaxMessages(10);
            //模型生成器-ModelBuilder,设置模型的每个可用参数
            //完整的模型参数设置 https://github.com/langchain4j/langchain4j-spring/blob/main/langchain4j-open-ai-spring-boot-starter/src/main/java/dev/langchain4j/openai/spring/AutoConfig.java
            ChatModel model = OpenAiChatModel.builder()
                    .baseUrl(baseUrl)
                    .apiKey(apikey)
                    .modelName(modelName)
                    .build();

            Assistant assistant = AiServices.builder(Assistant.class)
                    .chatModel(model)
                    .chatMemory(chatMemory)
                    .build();

            String answer = assistant.chat("Hello! My name is Klaus.");
            System.out.println(answer); // Hello Klaus! How can I assist you today?
            answerWithName = assistant.chat("What is my name?");
            System.out.println(answerWithName); // Your name is Klaus.
        }catch (Exception e) {
            System.out.println("记忆聊天异常,原因:" + e.getMessage());
        }
        return answerWithName;
    }
}
